package com.lemon.cloud.oauth.handler;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.lemon.cloud.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.lemon.cloud.comm.constants.OAuth2Constant.CUSTOM_CONSENT_LOGIN_PAGE;

@Slf4j
public class FormAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private String applicationName;

    public FormAuthenticationFailureHandler(String applicationName) {
        this.applicationName = applicationName;
    }
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.debug("表单登录失败:{}", exception.getLocalizedMessage());
        String url = HttpUtil.encodeParams(String.format(StrUtil.C_SLASH + applicationName+ CUSTOM_CONSENT_LOGIN_PAGE + "?error=%s", exception.getMessage()),
                CharsetUtil.CHARSET_UTF_8);
        WebUtils.getResponse().sendRedirect(url);
    }
}
